package org.apache.service.impl;

import java.util.Map;

import org.apache.dao.UserAccountDAO;
import org.apache.dto.Cookies;
import org.apache.model.UserAccount;
import org.apache.service.AbstractService;
import org.apache.service.UserAccountService;
import org.apache.util.Bet365;
import org.apache.util.Constant;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class UserAccountServiceImpl extends AbstractService implements UserAccountService, Constant, Bet365 {

    @Autowired
    private UserAccountDAO userAccountDAO;

    @Override
    public boolean isLogined(Cookies cookies, Map<String, String> headers) {

        try {
            Document memberAreaPage = redirectNavigator(DEFAULT_URL, headers, cookies);
            Element navMenu = memberAreaPage.select("#NavMenu").get(0);
            String balanceUrl = "";
            for (Element menu : navMenu.select("a")) {
                if (menu.html().equalsIgnoreCase(BALANCE)) {
                    balanceUrl = menu.attr("href");
                    break;
                }
            }
            if (!StringUtils.isEmpty(balanceUrl)) {
                Document balancePage = redirectNavigator(BASE_URL_1 + balanceUrl, headers, cookies);
                System.out.println(balancePage);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public Float getBalance() {

        UserAccount user = getUser();
        if (user != null) {
            return user.getBalance();
        }
        return 0F;
    }

    @Override
    public UserAccount getUser() {

        return userAccountDAO.getCurrentUser();
    }

}
